const logger = require('../helper/logger')

const tableName = 'access_token'

module.exports = async (db) => {
  try {
    const exists = await db.schema.hasTable(tableName)
    if (!exists) {
      await db.schema.createTable(tableName, (table) => {
        table.charset('utf8')
        table.increments('id')
        table.string('token', 64).unique()
        table.dateTime('expired_at').notNullable()
        table.integer('administrator_id').unsigned()
        table.foreign('administrator_id').references('id').inTable('administrator')
        table.integer('merchant_id').unsigned()
        table.foreign('merchant_id').references('id').inTable('merchant')
        table.integer('user_id').unsigned()
        table.foreign('user_id').references('id').inTable('user')
        table.enum('app', ['admin', 'merchant', 'client']).notNullable()
        table.enum('device', ['android', 'ios', 'web']).notNullable()
        table.string('app_version')
        table.string('device_version')
        table.timestamps(false, true)
      })
      logger.info(`Created ${tableName} table`)
      const items = [
        {
          token: 'fd4a5b8db5261dbd87ed758ef3c4ff08f1f1989fe55d9b3c59332328ba4916b1',
          expired_at: '2018-10-31 01:12:03',
          administrator_id: 1,
          app: 'admin',
          app_version: '0.0.0',
          device: 'web',
          device_version: 'Chrome 68.0.3440.106',
        },
      ]
      await db.batchInsert(tableName, items).then()
    }
  } catch (error) {
    logger.error(`Error creating ${tableName} table`, error)
  }
}
